package com.xmqian.app.project.ui.main

import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.Message
import android.widget.LinearLayout
import android.widget.TextView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.coszero.ui.dialog.ToastUtils
import com.coszero.utils.utils.LogX
import com.coszero.utils.utils.RandomUtils
import com.example.xmqian.R
import com.example.xmqian.databinding.ActivityMainBinding
import com.xmqian.app.project.common.base.BaseMyActivity
import com.xmqian.app.project.event.LoginEvent
import com.xmqian.app.project.ui.preview.activity.TestMainActivity
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class MainActivity : BaseMyActivity() {
    private var lastPressBackKeyTime: Long = 0
    var swipeRefreshLayout: SwipeRefreshLayout? = null
    var tvGo: TextView? = null
    private var handler: Handler? = null
    private var binding: ActivityMainBinding? = null

    @Suppress("deprecation")
    override fun initView() {
        swipeRefreshLayout = binding!!.swipeRefreshLayout
        tvGo = binding!!.tvGo
        handler = object : Handler() {
            override fun handleMessage(msg: Message) {
                tvGo!!.setTextColor(RandomUtils.getRandownColor())
                //                super.handleMessage(msg);
                handler!!.sendEmptyMessageDelayed(1, 1000)
            }
        }

        swipeRefreshLayout!!.setOnRefreshListener {
            handler.removeMessages(1)
            handler.sendEmptyMessage(1)
            swipeRefreshLayout!!.isRefreshing = false
        }
    }

    override fun initData() {
    }

    override fun onBackPressed() {
        if (System.currentTimeMillis() - lastPressBackKeyTime < DELAY_TIME) {
            super.onBackPressed()
        } else {
            lastPressBackKeyTime = System.currentTimeMillis()
            ToastUtils.showLongMsg(resources.getString(R.string.toast_press_again_exit_app))
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventLogin(event: LoginEvent) {
        if (event.isLogin) {
            LogX.i("### 登录成功")
        } else {
            LogX.i("### 退出登录成功")
        }
    }

    fun onClick() {
        startActivity(Intent(this, TestMainActivity::class.java))
        finish()
    }

    override fun onDestroy() {
        if (handler != null) {
            handler!!.removeMessages(1)
            handler!!.removeCallbacksAndMessages(null)
        }
        super.onDestroy()
    }

    override fun getLayoutView(): LinearLayout {
        binding = ActivityMainBinding.inflate(layoutInflater)
        return binding!!.root
    }

    companion object {
        private const val DELAY_TIME: Long = 1500 //退出间隔时间
        fun startActivity(context: Context) {
            val intent = Intent()
            intent.setClass(context, MainActivity::class.java)
            context.startActivity(intent)
        }
    }
}
